package top.jacktgq.hsp.netty.tcp_selfprotocal;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Author CandyWall
 * @Date 2020/11/13--17:47
 * @Description
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal msg) throws Exception {
        //服务器接收客户端发来的消息
        System.out.println("收到来自客户端的一条消息：" + msg);
        //服务器端给客户端回送一条消息，"有内鬼，终止交易"
        String message = "有内鬼，终止交易";
        byte[] messageBytes = message.getBytes();
        top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal messageProtocal = new top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal(messageBytes.length, messageBytes);
        ctx.writeAndFlush(messageProtocal);
    }

    @Override
    //处理异常情况
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常消息");
        ctx.close();
    }
}
